/**
 * 
 */
package com.demo2do.strawberry.service.impl;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.demo2do.core.persistence.GenericDaoSupport;
import com.demo2do.core.web.resolver.Page;
import com.demo2do.strawberry.entity.investor.Institution;
import com.demo2do.strawberry.service.InstitutionService;

/**
 * @author Downpour
 */
@Service("institutionService")
public class InstitutionServiceImpl implements InstitutionService {
	
	@Autowired
	private GenericDaoSupport genericDaoSupport;

	/* (non-Javadoc)
	 * @see com.demo2do.strawberry.service.InstitutionService#list(com.demo2do.core.web.resolver.Page, java.lang.String)
	 */
	@SuppressWarnings("unchecked")
	public List<Institution> list(Page page, String name) {
		
		String query = "";
		Map<String, Object> parameters = new HashMap<String, Object>();
		if(StringUtils.isNotEmpty(name)) {
			query = "SELECT institution FROM Institution institution, Profile profile WHERE institution.member = profile.member and profile.name like :name ORDER BY institution.id ASC";
			parameters.put("name", com.demo2do.core.utils.StringUtils.connect("%", name, "%"));
		} else {
			query = "FROM Institution institution ORDER BY institution.id ASC";
		}
		List<Institution> institutions = genericDaoSupport.searchForList(query, parameters, page.getBeginIndex(), page.getMaxResultRecords());
		page.calculate(institutions.size(), 0);
		return (institutions.size() >= page.getEveryPage()) ? institutions.subList(0, page.getEveryPage()) : institutions;
	}
	
	/* (non-Javadoc)
	 * @see com.demo2do.strawberry.service.InstitutionService#load(java.io.Serializable)
	 */
	public Institution load(Serializable id) {
		return genericDaoSupport.load(Institution.class, id);
	}
	
	/* (non-Javadoc)
	 * @see com.demo2do.strawberry.service.InstitutionService#loadAll()
	 */
	public List<Institution> loadAll() {
		return genericDaoSupport.loadAll(Institution.class);
	}
	
}